package com.ruoyi.web.controller.system;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.system.domain.*;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ProjectsService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


//项目信息
@RestController
@RequestMapping("/system/projects")
public class ProjectsController extends BaseController {
    @Autowired
    private ProjectsService projectsService;

    //项目列表查询
    @GetMapping("/list")
    public TableDataInfo list(Projects projects,@RequestHeader("userId")String userId) {
        projects.setUserId(userId);
        //拼接月份  先判断是否为空
        if (projects.getMouMouth() != null) {
            if (Integer.valueOf(projects.getMouMouth()) < 10) {
                projects.setMouMouth(0 + projects.getMouMouth());
            }
        }
        // 根据用户查询部门
        if(0==projects.getDeptId()){
            int deptId = projectsService.selectDept(projects.getUserId());
            //是否为政府部门
            //判断是否为admin
            if (deptId!=-1) {
                if (0 == projectsService.selectDeptId(projects.getUserId())) {
                    projects.setDeptId(-1);
                } else {
                    projects.setDeptId(deptId);
                }
            }
        }
        startPage();
        List<Projects> list = projectsService.selectProjectsList(projects);
        return getDataTable(list);
    }

    //查询是否为政府
    @PostMapping("/selectIsGovernMent")
    public Integer selectIsGovernMent(@RequestHeader("userId")String userId) {
        int selectDeptId = projectsService.selectDeptId(userId);
        return selectDeptId;
    }

    //项目下拉列表查询
    @PostMapping("/vague")
    public Vague list() {
        Vague vague = projectsService.selectVague();
        return vague;
    }

    //修改回显
    @PostMapping("/getPro")
    public AjaxResult getPro(Long proId) {
        Projects projects = projectsService.getPro(proId);
        return AjaxResult.success(projects);
    }

    //项目修改
    @Log(title = "项目修改", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@Validated @RequestBody Projects projects) {
        int num = projectsService.updateProjects(projects);
        if (num < 0) {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    //项目联系信息回显
    @GetMapping("/getProInf")
    public TableDataInfo getProInf(Contact contact) {
        startPage();
        List<Contact> proInf = projectsService.getProInf(contact.getProId());
        return getDataTable(proInf);

    }

    //项目联系信息新增
    @Log(title = "新增项目联系", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addContact(@RequestBody Contact contact) {
        return toAjax(projectsService.addContact(contact));
    }


    //项目联系信息修改
    @Log(title = "项目修改联系", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult editContact(@RequestBody Contact contact) {
        return toAjax(projectsService.updateContact(contact));
    }

    //项目联系信息删除
    @Log(title = "删除项目联系", businessType = BusinessType.DELETE)
    @DeleteMapping("/{conId}")
    public AjaxResult removeContact(@PathVariable Long conId) {
        return toAjax(projectsService.removeConById(conId));
    }

    //年度信息回显
    @GetMapping("/ProYear")
    public TableDataInfo getProYear(ProYear year) {
        startPage();
        List<ProYear> ProYear = projectsService.getProYear(year.getProId());
        return getDataTable(ProYear);
    }


    //返回所有业主单位
    @PostMapping("/getAllCon")
    public TableDataInfo getAllCon() {
        List<ContactType> ProYear = projectsService.getAllCon();
        return getDataTable(ProYear);

    }
    //月度信息


    //新增项目
    @Log(title = "新增项目", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody Projects projects,@RequestHeader("userId")String userId) {
        projects.setUserId(userId);
        int num = projectsService.insertProjects(projects);
        if (num < 0) {
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success("新增成功");

    }

    //删除项目
    @Log(title = "删除项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(Integer proId) {
        int num = projectsService.remove(proId);
        if (num < 0) {
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 导出项目列表
     */
//    @PreAuthorize("@ss.hasPermi('system:projects:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(HttpServletRequest request, HttpServletResponse response, Projects projects,@RequestHeader("userId")String userId) {
        try {
            // 循环数据
            projects.setUserId(userId);
            List<Projects> projects1 = projectsService.selectProjectsList(projects);
            List<Object> list = new ArrayList<>();
            // 表一数据
            for (int i = 0; i < projects1.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("proNum", projects1.get(i).getProNum());
                map.put("proName", projects1.get(i).getProName());
                map.put("proContent", projects1.get(i).getProContent());
                map.put("natName", projects1.get(i).getNatName());
                map.put("proInvest", projects1.get(i).getProInvest());
                map.put("mesInvest", projects1.get(i).getMesInvest());
                map.put("proIssue", projects1.get(i).getProIssue());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:MM:SS");
                map.put("mesInvestGoal", projects1.get(i).getMesInvestGoal());
                map.put("mesTotalGoal", projects1.get(i).getMesTotalGoal());
                map.put("mouRealInvest", projects1.get(i).getMouRealInvest());
                map.put("mouRealGoal", projects1.get(i).getMouRealGoal());
                map.put("proStrdate", dateFormat.format(projects1.get(i).getProStrdate()));
                map.put("proEnddate", dateFormat.format(projects1.get(i).getProEnddate()));
                map.put("contName", projects1.get(i).getContName());
                map.put("conName", projects1.get(i).getConName());
                map.put("domName", projects1.get(i).getDomName());
                map.put("deName", projects1.get(i).getDeName());
                list.add(map);
            }
            // 表格使用的数据
            Map map = new HashMap();
            map.put("data", list);//放入表一数据
            map.put("yeas", projects.getMouYear());//放入表一数据
            //读取模板
            TemplateExportParams params = new TemplateExportParams("//opt//server//wzzhgd//ruoyi-admin//src//main//resources//excel//导出项目明细模板.xlsx");
            //设置sheet名,以数组的形式,可多个
            params.setSheetName(new String[]{"项目明细"});
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        ExcelUtil excelUtil= new ExcelUtil();
        return new AjaxResult(1, "导出项目明细模板.xlsx");
    }


    @GetMapping("/DomesticContent")//大屏标点内容
    public AjaxResult selectDomesticContent(String proLongitude, String proDimensionality) {
        return AjaxResult.success(projectsService.selectDomesticContent(proLongitude, proDimensionality));
    }

    @ApiOperation(value = "项目导入")
    @Log(title = "项目导入", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload")
    @CrossOrigin
    public AjaxResult Upload(MultipartFile file,@RequestHeader("userId")String userId) {
        System.out.println("6666");
        if (projectsService.importExcel(file,userId)>0) {
            return AjaxResult.success("成功");
        } else {
            return AjaxResult.error("");
        }
    }

    //导入模板下载
    @GetMapping("/download")//下载
    private void respOutPutExcel(String fileName, HSSFWorkbook wb, HttpServletResponse resp) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            wb.write(os);
            System.out.println("导出excel成功");
            // 设置response参数，可以打开下载页面
            resp.reset();
            resp.setContentType("application/vnd.ms-excel;charset=utf-8");
            resp.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(( "xx.xls").getBytes(), "iso-8859-1"));
            ServletOutputStream out = resp.getOutputStream();
            File f = new File(System.getProperty("user.dir") + "//classes//excel//导入项目明细模板.xls");
            // 获取 Workbook ，传入 模板 和 数据 这里是读取的模板
            InputStream inputStream = new FileInputStream(f);
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally {
            try {
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    //文件转数组
    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    //项目监控列表查询
    @GetMapping("/Monitoring/list")
    public TableDataInfo Monitoringlist(ProjectMonitoring monitoring) {
        startPage();
        List<ProjectMonitoring> list = projectsService.queryMonitoring(monitoring);
        return getDataTable(list);
    }
    @GetMapping("/Monitoring/list2")
    public TableDataInfo Monitoringlist2(YsyCamerasself ysyCamerasself) {
        startPage();
        List<ProjectMonitoring> list = projectsService.selectYsyCamerasselfList(ysyCamerasself);
        return getDataTable(list);
    }
    @GetMapping("/Monitoring/list4")
    public TableDataInfo Monitoringlist2(Long proId) {
        startPage();
        List<YsyCamerasself> list = projectsService.querycamerabyproId(proId);
        return getDataTable(list);
    }
    @GetMapping("/Monitoring/list3")
    public TableDataInfo Monitoringlist3(YsyCamerasself ysyCamerasself) {
        startPage();
        List<YsyCamerasself> list = projectsService.querycamerabyareaid(ysyCamerasself);
        return getDataTable(list);
    }

    /**
     * 新增项目视频监控
     */
//    @PreAuthorize("@ss.hasPermi('system:monitoring:add')")
//    @Log(title = "项目视频监控", businessType = BusinessType.INSERT)
    @PostMapping(value = "/Monitoring/add")
    public AjaxResult addMonitoring(@RequestBody ProjectMonitoring projectMonitoring) {
        if (projectsService.addMonitoring(projectMonitoring) > 0) {
            return AjaxResult.success("添加成功");
        } else {
            return AjaxResult.error("添加失败");
        }
    }
    @PostMapping(value = "/Monitoring/add2")
    public AjaxResult addMonitoring2( Long proId,Long Id) {
        if (projectsService.addMonitoring2(proId,Id)> 0) {
            return AjaxResult.success("添加成功");
        } else {
            return AjaxResult.error("添加失败");
        }
    }
    @PostMapping(value = "/Monitoring/del")
    public AjaxResult delMonitoring2( Long proId,Long Id) {
        if (projectsService.delMonitoring2(proId,Id) > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }
    /**
     * 删除项目视频监控
     */
//    @PreAuthorize("@ss.hasPermi('system:monitoring:remove')")
    @Log(title = "项目视频监控", businessType = BusinessType.DELETE)
    @DeleteMapping("/Monitoring/{mIds}")
    public AjaxResult removeMonitoring(@PathVariable Long mIds) {
        return toAjax(projectsService.delMonitoring(mIds));
    }

}
